package com.stupidzhang.weixin.service;


import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.domain.kplunion.OrderService.request.query.OrderRowReq;
import com.jd.open.api.sdk.domain.kplunion.OrderService.response.query.OrderRowQueryResult;
import com.jd.open.api.sdk.domain.kplunion.OrderService.response.query.OrderRowResp;
import com.jd.open.api.sdk.domain.kplunion.StatisticsService.request.query.RedPacketEffectDataReq;
import com.jd.open.api.sdk.internal.JSON.JSON;
import com.jd.open.api.sdk.request.kplunion.UnionOpenOrderRowQueryRequest;
import com.jd.open.api.sdk.request.kplunion.UnionOpenStatisticsRedpacketQueryRequest;
import com.jd.open.api.sdk.response.kplunion.UnionOpenOrderRowQueryResponse;
import com.jd.open.api.sdk.response.kplunion.UnionOpenStatisticsRedpacketQueryResponse;
import com.stupidzhang.weixin.config.ZhiHuProperties;
import com.stupidzhang.weixin.constant.JdConstants;
import com.stupidzhang.weixin.mode.EntityBase;
import com.stupidzhang.weixin.mode.WeiXinMessageEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 京东订单查询接口
 */
@Service
@Slf4j
public class JingFenApiService {


    @Autowired
    private ZhiHuProperties zhihuProperties;

    /**
     * 查询型订单
     *
     * @param startTime
     * @param endTime
     */
    public WeiXinMessageEntity queryOrderList(String startTime, String endTime) {
        JdClient client = getJdClient();
        UnionOpenOrderRowQueryRequest request = new UnionOpenOrderRowQueryRequest();
        OrderRowReq orderReq = new OrderRowReq();
        orderReq.setStartTime(startTime);
        orderReq.setEndTime(endTime);
        orderReq.setPageIndex(1);
        orderReq.setPageSize(10);
        orderReq.setType(1);
        request.setOrderReq(orderReq);
        request.setVersion(JdConstants.VERSION);
        UnionOpenOrderRowQueryResponse response;
        try {
            response = client.execute(request);
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            log.error("请求京粉接口出错了呀！！！");
            return null;
        }
        OrderRowQueryResult queryResult = response.getQueryResult();
        List<OrderRowResp> orderList = Arrays.asList(queryResult.getData());
        if (orderList.isEmpty()) {
            log.info("没有获取到数据，请继续保持持续输出~~");
            return null;
        }
        orderList = orderList.stream().filter(order -> order.getParentId() == 0)
                .filter(order -> order.getValidCode() == 16 || order.getValidCode() == 17).collect(Collectors.toList());
        if (orderList.isEmpty()) {
            log.warn("非常遗憾，新增订单为无效订单，订单详情：{}", JSON.toString(orderList));
            return null;
        }
        return buildOrder(orderList);
    }




    public void queryRedpacketList(String startTime, String endTime) {
        JdClient client = getJdClient();
        UnionOpenStatisticsRedpacketQueryRequest request = new UnionOpenStatisticsRedpacketQueryRequest();
        RedPacketEffectDataReq effectDataReq = new RedPacketEffectDataReq();
        request.setEffectDataReq(effectDataReq);
        effectDataReq.setStartDate(startTime);
        effectDataReq.setEndDate(endTime);
        effectDataReq.setPageIndex(1);
        effectDataReq.setPageSize(10);
        effectDataReq.setPositionId(1L);
        request.setVersion(JdConstants.VERSION);
        try {
            UnionOpenStatisticsRedpacketQueryResponse response = client.execute(request);
        } catch (Exception e) {


        }
    }

    /**
     * 获取客户端
     *
     * @return
     */
    private JdClient getJdClient() {
        JdClient client = new DefaultJdClient(JdConstants.JD_API_URL, "", zhihuProperties.getAppKey(), zhihuProperties.getAppSecret());
        return client;
    }


    /**
     * 构建实体
     *
     * @param orderList 订单列表
     * @return omit
     */
    private WeiXinMessageEntity buildOrder(List<OrderRowResp> orderList) {
        // 订单数量
        int orderNum = orderList.size();
        double estimateFee = orderList.stream().mapToDouble(OrderRowResp::getEstimateFee).sum();
        double eEstimateCosPrice = orderList.stream().mapToDouble(OrderRowResp::getEstimateCosPrice).sum();
        WeiXinMessageEntity order = new WeiXinMessageEntity();
        order.setFirst(new EntityBase(String.valueOf(orderNum), "#5d6375"));
        order.setKeyword1(new EntityBase(String.valueOf(estimateFee), "#9e0606"));
        order.setKeyword2(new EntityBase(String.valueOf(eEstimateCosPrice), "#5d6375"));
        StringBuilder contentBuilder = new StringBuilder();
        AtomicInteger orderSeq = new AtomicInteger(1);
        orderList.forEach(orderRowResp -> {
            String skuName = orderRowResp.getSkuName();
            Integer plus = orderRowResp.getPlus();
            Integer traceType = orderRowResp.getTraceType();
            String traceTypeName = traceType == 2 ? "同店" : "跨店";
            // 订单类型
            String unionTag = orderRowResp.getUnionTag();
            log.info("您有新订单啦，商品名称：{}, 金额：{}", skuName, estimateFee);

            contentBuilder.append("【").append(traceTypeName);
            if (plus == 1) {
                contentBuilder.append("-").append("PLUS");
            }
            if (unionTag.contains("红包")) {
                contentBuilder.append("-").append("红包订单");
            }
            contentBuilder.append("】");
            contentBuilder.append(orderSeq.getAndIncrement()).append("、")
                    .append(StringUtils.substring(skuName, 0, Math.min(skuName.length(), 50)))
                    .append("...").append("\n");
        });
        order.setKeyword3(new EntityBase(contentBuilder.toString(), "#5d6375"));
        return order;
    }


}
